#include "TabChat.h"
#include "ChatPrompt.h"
#include "PromptEditor.h"
#include "PromptInfo.h"
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QUrl>
#include <QVBoxLayout>

TabChat::TabChat(QWidget *parent)
    : QWidget(parent), m_openaiManager(OpenaiManager::getInstance()), m_logOutput(nullptr)
{
    // 确保chat_prompt.json所在目录存在
    QString promptDir = QFileInfo(ChatPrompt::getInstance()->getPromptPath()).path();
    if (!QDir(promptDir).exists())
    {
        QDir().mkpath(promptDir);
    }

    createUI();
}

void TabChat::createUI()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 聊天内容区域
    QGroupBox *chatGroup    = new QGroupBox("AI聊天", this);
    QVBoxLayout *chatLayout = new QVBoxLayout(chatGroup);

    // 输出框
    m_outputEdit = new QTextEdit(this);
    m_outputEdit->setReadOnly(true);
    m_outputEdit->setPlaceholderText("AI回答将显示在这里...");
    chatLayout->addWidget(m_outputEdit);

    // 输入框
    m_inputEdit = new QTextEdit(this);
    m_inputEdit->setPlaceholderText("在此输入问题，按Ctrl+Enter发送...");
    m_inputEdit->setMaximumHeight(100);
    chatLayout->addWidget(m_inputEdit);

    // 按钮区域
    QHBoxLayout *buttonLayout = new QHBoxLayout();

    m_keepHistoryCheck = new QCheckBox("保留历史记录", this);
    m_keepHistoryCheck->setChecked(true);

    m_editPromptButton   = new QPushButton("编辑提示", this);
    m_clearHistoryButton = new QPushButton("清除历史", this);
    m_sendButton         = new QPushButton("发送", this);

    buttonLayout->addWidget(m_keepHistoryCheck);
    buttonLayout->addWidget(m_editPromptButton);
    buttonLayout->addWidget(m_clearHistoryButton);
    buttonLayout->addStretch();
    buttonLayout->addWidget(m_sendButton);

    chatLayout->addLayout(buttonLayout);
    mainLayout->addWidget(chatGroup);

    // 设置快捷键
    m_sendShortcut = new QShortcut(QKeySequence("Ctrl+Return"), this);

    // 连接信号槽
    connect(m_sendButton, &QPushButton::clicked, this, &TabChat::onSendClicked);
    connect(m_editPromptButton, &QPushButton::clicked, this, &TabChat::onEditPromptClicked);
    connect(m_sendShortcut, &QShortcut::activated, this, &TabChat::handleShortcut);
    connect(m_clearHistoryButton, &QPushButton::clicked, this, &TabChat::clearHistory);
}

void TabChat::startChat(const QString &url, const QString &apiKey, const QString &model)
{
    // 验证参数
    if (url.isEmpty() || apiKey.isEmpty() || model.isEmpty())
    {
        emit logMessage("错误：URL、API Key或模型名称为空");
        QMessageBox::warning(this, "错误", "请先在AI服务设置中配置正确的API参数");
        return;
    }

    // 验证URL格式
    QUrl qurl(url);
    if (!qurl.isValid())
    {
        emit logMessage("错误：无效的URL格式: " + url);
        QMessageBox::warning(this, "错误", "无效的URL格式，请检查AI服务设置");
        return;
    }

    m_currentUrl    = url;
    m_currentApiKey = apiKey;
    m_currentModel  = model;

    QString question = m_inputEdit->toPlainText().trimmed();
    if (question.isEmpty())
    {
        QMessageBox::warning(this, "警告", "请输入问题内容");
        return;
    }

    // 获取ChatPrompt实例的提示信息
    ChatPrompt *prompt    = ChatPrompt::getInstance();
    PromptInfo promptInfo = prompt->getPrompt();

    // 处理用户提示列表
    QVector<QString> processedUserPrompts;
    QVector<QString> processedAssistantPrompts;

    // 增加参考示例
    for (const QString &userPrompt : promptInfo.userPromptList)
    {
        QString processedPrompt = buildPrompt(userPrompt, promptInfo);
        processedUserPrompts.append(processedPrompt);
    }

    for (const QString &assistantPrompt : promptInfo.assistantPromptList)
    {
        processedAssistantPrompts.append(assistantPrompt);
    }

    // 添加历史记录到提示中
    if (m_keepHistoryCheck->isChecked() && !m_history.isEmpty())
    {
        for (const ChatHistory &history : m_history)
        {
            processedUserPrompts.append(history.question);
            processedAssistantPrompts.append(history.answer);
        }
    }

    // 构建当前段落的翻译提示
    QString currentPrompt = buildPrompt(question, promptInfo);

    // 创建新的用户提示列表，包含所有处理过的示例和当前段落
    QVector<QString> finalUserPrompts = processedUserPrompts;
    finalUserPrompts.append(currentPrompt);

    emit logMessage("发送问题: " + question);
    emit logMessage("使用URL: " + m_currentUrl);
    emit logMessage("使用模型: " + m_currentModel);

    // 发送请求
    QString response = m_openaiManager->sendMessage(m_currentUrl, m_currentApiKey, m_currentModel,
                                                    promptInfo.prompt, finalUserPrompts,
                                                    processedAssistantPrompts);

    if (!response.isEmpty())
    {
        m_outputEdit->append("问: \n" + currentPrompt);
        m_outputEdit->append("答: \n" + response);
        m_outputEdit->append("\n");
        m_inputEdit->clear();

        // 添加到历史记录
        addHistory(currentPrompt, response);

        emit logMessage("成功获取AI回答");
    }
    else
    {
        emit logMessage("获取AI回答失败");
        QMessageBox::warning(this, "错误", "获取AI回答失败，请检查网络连接和API设置");
    }
}

void TabChat::onSendClicked()
{
    QString question = m_inputEdit->toPlainText().trimmed();
    if (question.isEmpty())
    {
        QMessageBox::warning(this, "警告", "请输入问题内容");
        return;
    }

    // 发送请求 会在startChat中处理
    emit requestChat();
}

void TabChat::onEditPromptClicked()
{
    ChatPrompt *prompt = ChatPrompt::getInstance();
    PromptEditor editor(prompt, this);
    editor.exec();
}

void TabChat::handleShortcut()
{
    onSendClicked();
}

void TabChat::updateLog(const QString &log)
{
    if (m_logOutput)
    {
        m_logOutput->appendPlainText(log);
    }
    emit logMessage(log);
}

void TabChat::addHistory(const QString &question, const QString &answer)
{
    if (m_keepHistoryCheck->isChecked())
    {
        // 添加新记录
        ChatHistory history;
        history.question = question;
        history.answer   = answer;

        // 如果超过最大数量，删除最早的记录
        if (m_history.size() >= MAX_HISTORY)
        {
            m_history.removeFirst();
        }

        m_history.append(history);
        emit logMessage("已添加新的聊天记录");
    }
}

void TabChat::clearHistory()
{
    m_history.clear();
    m_outputEdit->clear();
    emit logMessage("已清除所有聊天记录");
}

QString TabChat::buildPrompt(const QString &content, const PromptInfo &promptInfo)
{
    QString fullPrompt;

    // 添加聊天前缀
    if (!promptInfo.chatPrefix.isEmpty())
    {
        fullPrompt += promptInfo.chatPrefix + "\n\n";
    }

    // 添加需要翻译的内容
    fullPrompt += content + "\n\n";

    // 添加聊天后缀
    if (!promptInfo.chatSuffix.isEmpty())
    {
        fullPrompt += promptInfo.chatSuffix;
    }

    return fullPrompt;
}